package tms.presentation.converter;

import tms.util.jsf.FacesContextManager;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import java.util.Formatter;

@FacesConverter("totalTime")
public class TotalTimeConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        Long retVal = null;
        if (s != null && s.matches("\\d{1,2}:\\d{1,2}")) {
            String[] tokens = s.split(":");
            try {
                long hours = Long.parseLong(tokens[0]);
                long minutes = Long.parseLong(tokens[1]);
                retVal = hours * (60 * 60 * 1000) + minutes * (60 * 1000);
            } catch (NumberFormatException e) {
                processConversionError();
            }
        } else {
            processConversionError();
        }
        return retVal;
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
        String retVal = "";
        if (o != null && o instanceof Long) {
            long total = (Long)o;
            long hours = (total - (total % (60 * 60 * 1000))) / (60 * 60 * 1000);
            long minutes = (total % (60 * 60 * 1000)) / (60 * 1000);

            StringBuilder sb = new StringBuilder();
            Formatter formatter = new Formatter(sb);
            formatter.format("%1$02d:%2$02d", hours, minutes);

            retVal = sb.toString();
        }

        return retVal;
    }

    private void processConversionError() {
        FacesContextManager facesContextManager = new FacesContextManager();
        throw new ConverterException(facesContextManager.evaluateExpression("#{facesContextManager.buildFacesMessage(localizer.localized('TIME_CONVERTION_ERROR'))}", FacesMessage.class));
    }
}
